//
//  AppDelegate.m
//  Client
//
//  Created by 顾悦 on 16/3/21.
//
//

#import "AppDelegate.h"

#import "JPUSHService.h"
#import "WXApi.h"
#import "WXApiManager.h"

#import "ThemeColor.h"

#import "UserInfoController.h"

#import "HomeViewController.h"
#import "ClientWebViewController.h"

static NSString *appKey = @"409cd3aca758dfad7db98411";
static NSString *channel = @"App Store";
static BOOL isProduction = YES;

@interface AppDelegate () <UITabBarControllerDelegate>

@end

@implementation AppDelegate

- (UITabBarController *)tabBarController {
    return (UITabBarController *)self.window.rootViewController;
}

- (HomeViewController *)homeViewController {
    return (HomeViewController *)((UINavigationController *)[self tabBarController].viewControllers[0]).viewControllers[0];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // appearance
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.window.tintColor = [ThemeColor orangeColor];
    [UINavigationBar appearance].translucent = NO;
    [UINavigationBar appearance].barTintColor = [ThemeColor orangeColor];
    [UINavigationBar appearance].tintColor = [UIColor whiteColor];
    [UINavigationBar appearance].titleTextAttributes = @{NSFontAttributeName: [UIFont systemFontOfSize:17.0], NSForegroundColorAttributeName: [UIColor whiteColor]};
    /*
    
    [UITabBar appearance].selectionIndicatorImage = [UIImage imageNamed:@"HomeTabBarIndicator"];
     */
    [UIPageControl appearance].currentPageIndicatorTintColor = [ThemeColor orangeColor];
    [UIPageControl appearance].pageIndicatorTintColor = [UIColor whiteColor];
    
    //
    
    [self tabBarController].delegate = self;
    
    // push notifications
    
    UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    
    [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                      UIUserNotificationTypeSound |
                                                      UIUserNotificationTypeAlert)
                                          categories:nil];
    
    [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel apsForProduction:isProduction];
    
    NSDictionary *userInfo = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [self tryToGoToMsgCenter];
    }
    
    // WeChat payment
    
    [WXApi registerApp:@"wxb99bc37fe411b491" withDescription:@"悦帮iOS客户端"];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    // Mark
    
    [UserInfoController setIsClient:YES];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
    if (viewController == tabBarController.viewControllers[0]) {
        return YES;
    } else {
        if ([UserInfoController isLogin]) {
            return YES;
        } else {
            [[self homeViewController] pushLoginViewControllerCompletionHandler:^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    tabBarController.selectedViewController = viewController;
                    [[self homeViewController].navigationController popViewControllerAnimated:NO];
                });
            }];
            return NO;
        }
    }
}

- (void)tryToGoToMsgCenter {
    if ([UserInfoController isLogin]) {
        ClientWebViewController *webViewController = ClientWebViewController.new;
        webViewController.HTMLURL = @"user/systemNotify.html";
        webViewController.hidesBottomBarWhenPushed = YES;
        [[self tabBarController].viewControllers.firstObject pushViewController:webViewController animated:YES];
    }
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
//    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [UserInfoController setDeviceToken:deviceToken];
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [JPUSHService handleRemoteNotification:userInfo];
    if (application.applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"通知" message:userInfo[@"aps"][@"alert"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }

}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
}

@end
